import { Injectable } from '@nestjs/common';
import { Analytics, EventType, User } from '../entities';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

const EventTypeDescriptions: Record<EventType, string> = {
  [EventType.DIET_LOG]: '饮食记录事件',
  [EventType.NUTRITION_ANALYSIS]: '营养分析事件',
  [EventType.NUTRITION_EDUCATION]: '营养教育事件',
  [EventType.ANTI_INFLAMMATORY_RANKING]: '抗炎食物排行事件',
  [EventType.PROFILE_VIEW]: '我的信息事件',
  [EventType.VISIT]: '访客事件',
  [EventType.CHECK_IN]: '打卡事件',
};
@Injectable()
export class AnalyticsService {
  constructor(
    @InjectRepository(Analytics)
    private readonly analyticsRepository: Repository<Analytics>,
  ) {}
  create(userId: number, eventType: EventType) {
    const createAnalytics = this.analyticsRepository.create({ 
      userId,
      eventType: eventType,
      module: EventTypeDescriptions[eventType],
    });
    return this.analyticsRepository.save(createAnalytics);
  }

  async summary() {
    const queryBuilder = this.analyticsRepository
      .createQueryBuilder('analytics')
      // 字段, 别名
      .select('analytics.eventType', 'eventType')
      .addSelect('COUNT(*)', 'count')
      .groupBy('analytics.eventType');

    const result = await queryBuilder.getRawMany();

    // TODO, eventType中为 view 的过滤出今天的
    return result.map((item) => ({
      eventType: item.eventType,
      count: parseInt(item.count, 10),
      module: item.module,
    }));
  }

  update(id: number, updateAnalyticsDto: any) {
    return `This action updates a #${id} analytics`;
  }

  remove(id: number) {
    return `This action removes a #${id} analytics`;
  }
}
